package com.fishbone.psd.util;

import com.fishbone.psd.core.Layer;
import com.fishbone.psd.core.LayersContainer;
import com.fishbone.psd.core.Psd;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @ClassName HaPsdToImage
 * @Author huyaxi
 * @DATE 2020/7/22 16:16
 */
public class PsdToImageUtil {

    public static void main(String[] args) throws IOException{
        FileOutputStream outputStream = new FileOutputStream("F:\\ds.png");
        file2Jpeg(new File("F:\\ds.psd"),"png",outputStream);
        outputStream.close();
    }

    /**
     * psd文件流操作
     * @param inputStream
     * @param outputStream
     * @throws IOException
     */
    public static void stream2Jpeg(InputStream inputStream,String formatName,OutputStream outputStream) throws IOException{
       psdParser(new Psd(inputStream),formatName,outputStream);
    }


    /**
     * psd文件操作
     * @param file
     * @param outputStream
     * @throws IOException
     */
    public static void file2Jpeg(File file,String formatName,OutputStream outputStream) throws IOException{
        psdParser(new Psd(file),formatName,outputStream);
    }


    /**
     *
     * @param psd
     * @param formatName
     * @param outputStream
     * @throws IOException
     */
    private static void psdParser(Psd psd,String formatName,OutputStream outputStream) throws IOException {
        BufferedImage image = new BufferedImage(psd.getWidth(),psd.getHeight(),BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        paintLayersContainer(graphics,psd,1.0f);
        ImageIO.write(image,formatName,outputStream);
    }


    /**
     * 绘制psd到BufferImage
     * @param g
     * @param container
     * @param alpha
     */
    private static void paintLayersContainer(Graphics2D g, LayersContainer container, float alpha) {
        for (int i = 0; i < container.getLayersCount(); i++) {
            Layer layer = container.getLayer(i);
            if (!layer.isVisible()) {
                continue;
            }

            Composite composite = g.getComposite();
            float layerAlpha = alpha * layer.getAlpha() / 255.0f;
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, layerAlpha));

            if (layer.getImage() != null) {
                g.drawImage(layer.getImage(), layer.getX(), layer.getY(), null);
            }
            g.setComposite(composite);

            paintLayersContainer(g, layer, layerAlpha);
        }
    }
}
